const cloud = require('wx-server-sdk');

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});

// user.query(openid).get, 如果没有就注册

const db = cloud.database()
const User = db.collection('Users')

async function register (openid) {
    // 写入用户数据
    let ret = await User.add({
        data: {
            _openid: openid,
            create_time: new Date(),
            status: 1,
        }
    })
    if (ret._id) {
        return await find(openid)
    }
}

async function find (openid) {
    let user = await User.where({
        _openid: openid
    }).get()
    if (user.data.length == 0) {
        return await register(openid)
    } else {
        return user.data[0]
    }
}

// 获取openId云函数入口函数
exports.main = async (event, context) => {
    const { OPENID } = cloud.getWXContext()
    return await find(OPENID)
};
